<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" id="upload" />

    <script>
      // 2. 封装xhr请求
      function request({ url, method = 'POST', data, headers = {} }) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open(method, url);
          Object.keys(headers).map((key) => {
            xhr.setRequestHeader(key, headers[key]);
          });
          xhr.send(data);
          xhr.onload = (e) => {
            console.log(11, e);
            resolve({ data: e.target.response });
          };
        });
      }

      request({ url: 'http://localhost:3000/' }).then(
        (res) => {
          console.log(res);
        },
        (err) => {
          console.log('err: ', e);
        }
      );

      document.getElementById('upload').addEventListener('change', (e) => {
        e.preventDefault();
        const originFile = e.target.files[0];
        const fileName = originFile.name.split('.')[0];

        let currentSize = 0;
        const perSize = 0.5 * 1024 * 1024;
        const fileChunkList = [];
        while (currentSize < originFile.size) {
          fileChunkList.push({ file: originFile.slice(currentSize, currentSize + perSize) });
          currentSize += perSize;
        }

        const requestChunkList = fileChunkList.map(({ file }, index) => {
          const formData = new FormData();
          formData.append('chunk', file);
          formData.append('fileName', `${fileName}-${index}`);
          return formData;
        });
      });
    </script>
  </body>
</html>
